import {ref, reactive, computed, watch} from 'vue';
import { cloneDeep } from 'lodash-es';
import Request from '@/utils/Request';
import { useNotificationStore } from '@/stores/notification';
import { useRoute } from 'vue-router';

// 导出这个 composable 函数
export function useWorkoutPlan() {
    // --- 状态 (保持不变) ---
    const notificationStore = useNotificationStore();
    const loading = ref(true);
    const error = ref(null);
    const weeklyPlan = ref(null);
    const editablePlan = ref(null);
    const isEditMode = ref(false);
    const openedPanels = ref([]);
    const alternativeExercises = ref([]);
    const route = useRoute();

    const replaceDialog = reactive({
        show: false,
        dayIndex: -1,
        exIndex: -1,
        originalExerciseName: '',
        isLoadingAlternatives: false,
    });

    const logDialog = reactive({
        show: false,
        planId: null,
        workoutDate: null, // 【修复】打卡时使用 VO 中返回的 'date' 属性
        workoutName: '',
        feedback: 3,
        dayRef: null,
    });

    const badgeDialog = reactive({
        show: false,
        name: '',
        description: '',
    });

    // --- 【!! 核心修复 1 !!】 ---
    // 计算属性
    const sortedDailyWorkouts = computed(() => {
        const plan = editablePlan.value;
        if (!plan || !plan.dailyWorkouts) return [];
        // 【修复】后端 V3 VO (BaseWorkoutPlanHandler)
        // 保证返回的 dailyWorkouts.dayOffset 是 0-6 (周一到周日)
        return [...plan.dailyWorkouts].sort((a, b) => a.dayOffset - b.dayOffset);
    });

    // --- 方法 ---
    const fetchWeeklyPlan = () => {
        loading.value = true;
        error.value = null;

        const planId = route.params.planId;
        const url = planId
            ? `/workouts/plan/${planId}` // (API 正确)
            : '/workouts/plan/weekly';   // (API 正确)

        Request.get(url)
            .then(response => {
                const planPayload = response.data;

                // 【修复】我们重构的 C# V3 VO (WeeklyPlanVo)
                // 保证了数据结构统一 (dailyWorkouts)
                if (planPayload && planPayload.dailyWorkouts) {
                    planPayload.dailyWorkouts.forEach(day => {
                        day.isLogging = false;
                        day.isSaving = false;
                    });

                    weeklyPlan.value = planPayload;
                    editablePlan.value = cloneDeep(planPayload);

                    // (新增) 默认展开今天
                    const todayOffset = new Date().getDay(); // 0=周日, 1=周一
                    const targetOffset = (todayOffset === 0) ? 6 : todayOffset - 1; // 转为 0=周一 ... 6=周日
                    openedPanels.value = [targetOffset];

                } else {
                    throw new Error('未能获取到有效的运动计划数据。');
                }
            })
            .catch(err => {
                error.value = err.message || '加载运动计划失败';
            })
            .finally(() => {
                loading.value = false;
            });
    };

    // (watch 逻辑保持不变)
    watch(() => route.params.planId, (newPlanId, oldPlanId) => {
        if (newPlanId !== oldPlanId) {
            fetchWeeklyPlan();
        }
    });

    // (adjustSets, removeExercise, openReplaceDialog, replaceExercise 逻辑保持不变)
    // 注意：这些只修改本地 'editablePlan'，不调用 API
    const adjustSets = (dayIndex, exIndex, delta) => {
        const day = sortedDailyWorkouts.value[dayIndex];
        const exercise = day.exercises[exIndex];
        const parts = exercise.setsAndReps.split(' x ');
        let sets = parseInt(parts[0]);
        sets = Math.max(1, sets + delta);
        exercise.setsAndReps = `${sets} x ${parts[1]}`;
    };
    const removeExercise = (dayIndex, exIndex) => {
        sortedDailyWorkouts.value[dayIndex].exercises.splice(exIndex, 1);
    };
    const openReplaceDialog = (dayIndex, exIndex) => {
        const exercise = sortedDailyWorkouts.value[dayIndex].exercises[exIndex];
        Object.assign(replaceDialog, {
            dayIndex, exIndex, originalExerciseName: exercise.name,
            isLoadingAlternatives: true, show: true
        });
        // API (/api/exercises) (保持不变)
        Request.get('/exercises', { params: { bodyPart: exercise.bodyPart } })
            .then(res => {
                alternativeExercises.value = res.data.filter(ex => ex.id !== exercise.id);
            })
            .catch(err => {
                console.error(err);
                replaceDialog.show = false;
            })
            .finally(() => {
                replaceDialog.isLoadingAlternatives = false;
            });
    };
    const replaceExercise = (newExercise) => {
        const { dayIndex, exIndex } = replaceDialog;
        const oldExercise = sortedDailyWorkouts.value[dayIndex].exercises[exIndex];
        sortedDailyWorkouts.value[dayIndex].exercises[exIndex] = {
            ...newExercise,
            setsAndReps: oldExercise.setsAndReps,
            restSeconds: oldExercise.restSeconds
        };
        replaceDialog.show = false;
    };

    // --- 【!! 核心修复 2 !!】 ---
    const cancelEditing = (dayIndex) => {
        if (window.confirm('您有未保存的修改，确定要取消吗？')) {
            // 【修复】使用 dayOffset 查找原始数据
            const originalDay = weeklyPlan.value.dailyWorkouts.find(d => d.dayOffset === sortedDailyWorkouts.value[dayIndex].dayOffset);
            if (originalDay) {
                // 还原 editablePlan 中的对应项
                const indexInEditable = editablePlan.value.dailyWorkouts.findIndex(d => d.dayOffset === originalDay.dayOffset);
                if(indexInEditable > -1) {
                    editablePlan.value.dailyWorkouts[indexInEditable] = cloneDeep(originalDay);
                }
            }
            isEditMode.value = false;
        }
    };

    // --- 【!! 核心修复 3 !!】 ---
    const saveChanges = (dayIndex) => {
        const day = sortedDailyWorkouts.value[dayIndex];
        day.isSaving = true;
        const payload = {
            // (DTO 结构保持不变)
            updatedItems: day.exercises.map(ex => ({
                exerciseId: ex.id,
                sets: parseInt(ex.setsAndReps.split(' x ')[0]),
                reps: ex.setsAndReps.split(' x ')[1].trim(),
            }))
        };

        // 【!! 关键 API 修复 !!】
        // 我们在 10:04 AM 将 C# API 路由修改为:
        // [HttpPut("plan/{planId:guid}/day/{dayOffset:int}")]
        // 因此，这里必须传递 day.dayOffset (0-6)
        Request.put(`/workouts/plan/${editablePlan.value.planId}/day/${day.dayOffset}`, payload)
            .then(() => {
                // (逻辑不变)
                const indexInWeekly = weeklyPlan.value.dailyWorkouts.findIndex(d => d.dayOffset === day.dayOffset);
                if(indexInWeekly > -1) {
                    weeklyPlan.value.dailyWorkouts[indexInWeekly] = cloneDeep(day);
                }
                notificationStore.success('计划修改已保存！');
                isEditMode.value = false;
            })
            .catch(err => console.error(err))
            .finally(() => day.isSaving = false);
    };

    // --- 【!! 核心修复 4 !!】 ---
    const openLogDialog = (day) => {
        Object.assign(logDialog, {
            planId: weeklyPlan.value?.planId,
            // 【修复】使用后端 V3 VO 提供的 'date' (YYYY-MM-DD)，这更准确
            workoutDate: day.date,
            workoutName: day.workoutName,
            feedback: 3,
            dayRef: day,
            show: true
        });
    };

    // (handleLogWorkout 逻辑保持不变, API /api/workouts/log 正确)
    const handleLogWorkout = () => {
        if (logDialog.dayRef?.isLogging) return;
        logDialog.dayRef.isLogging = true;
        const payload = {
            planId: logDialog.planId,
            workoutDate: logDialog.workoutDate,
            userFeedback: Math.floor((logDialog.feedback - 1) / 2)
        };
        Request.post('/workouts/log', payload)
            .then(res => {
                logDialog.show = false;
                logDialog.dayRef.isCompleted = true; // (这个在 V3 VO 中已弃用，但前端状态可以保留)
                const unlocked = res.data.unlockedBadges;
                if (unlocked && unlocked.length > 0) {
                    Object.assign(badgeDialog, { ...unlocked[0], show: true });
                } else {
                    notificationStore.success('打卡成功，继续加油！');
                }
            })
            .catch(err => console.error(err))
            .finally(() => logDialog.dayRef.isLogging = false);
    };

    const playVideo = (url) => {
        window.open(url, '_blank');
    };

    // --- 【!! 核心修复 5 !!】 ---
    // C# 后端 (BaseWorkoutPlanHandler) 保证 0=周一, 6=周日
    const formatDayOfWeek = (dayOffset) => {
        const days = {
            0: '星期一', 1: '星期二', 2: '星期三',
            3: '星期四', 4: '星期五', 5: '星期六', 6: '星期日'
        };
        return days[dayOffset] || '未知';
    };

    // --- 暴露接口 (保持不变) ---
    return {
        loading, error, editablePlan, isEditMode, sortedDailyWorkouts,
        openedPanels, logDialog, badgeDialog, replaceDialog, alternativeExercises,
        fetchWeeklyPlan, adjustSets, removeExercise, openReplaceDialog, replaceExercise,
        cancelEditing, saveChanges, openLogDialog, handleLogWorkout, playVideo, formatDayOfWeek,
    };
}